﻿// $ PURE $ // class name and mean

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using ScintillaNET;

namespace CodeTable
{
    class BlockAutosize : Scintilla
    {
        static private Size fontLetterSize = new Size(8, 18);
        static private Size fontSpaceSize = new Size(10, 18);
        static private Size minClientSize = new Size(80, 20);

        public BlockAutosize(string name, Scintilla prototype)
        {
            Utils.MakeScintillaClone(prototype, this);
            this.Name = name;

            // WARNING: this class supports manual sizing ONLY.
            System.Diagnostics.Trace.Assert(this.Font.SizeInPoints == 12, "Unsupported font size");
        }

        protected override void OnTextChanged(EventArgs e)
        {
            Size newClientSize = GetControlClientSize(this.Text, this.Margins);
            if (this.ClientSize != newClientSize)
            {
                this.ClientSize = newClientSize;
            }

            base.OnTextChanged(e);
        }

        static private Size GetTextSize(string text)
        {
            string[] lines = text.Split(new string[] { "\n" }, StringSplitOptions.None);
            int maxLineIndex = 0;
            for (int i = 1; i < lines.Length; ++i)
            {
                if (lines[maxLineIndex].Length < lines[i].Length)
                    maxLineIndex = i;
            }
            string maxLine = lines[maxLineIndex];
            int lettersCount =  maxLine.Replace(" ", "").Length;
            int spacesCount = maxLine.Length - lettersCount;
            return new Size(lettersCount * fontLetterSize.Width + spacesCount * fontSpaceSize.Width, lines.Length * fontLetterSize.Height);
        }

        static public Size GetControlClientSize(string text, MarginCollection margins)
        {
            int marginsWidth = margins.Left;
            for (int i = 0; i < margins.Count; ++i)
            {
                marginsWidth += margins[i].Width;
            }
            marginsWidth += margins.Right;
            Size textSize = GetTextSize(text);
            Size controlSize = new Size(
                1 + marginsWidth + textSize.Width + fontSpaceSize.Width + 1,
                1 + textSize.Height + 1
            );
            if (controlSize.Width < minClientSize.Width)
                controlSize.Width = minClientSize.Width;
            if (controlSize.Height < minClientSize.Height)
                controlSize.Height = minClientSize.Height;
            return controlSize;
        }
    }
}
